package com.inkkpot.prettyprint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.opensymphony.xwork2.ActionSupport;

public class PrettyPrintAction extends ActionSupport implements ServletResponseAware{
	private static final Logger log = Logger.getLogger(PrettyPrintAction.class.getName());

	private String url;
	private String output;

	private HttpServletResponse response;

	public String getPage(){
		response.setContentType("text/html");
		try{
			PrintWriter pw = response.getWriter();
			String pageContent = readUrl();
			if(pageContent == null || pageContent.length()==0){
				output="Page Not Found";
			}else{
				output = PrettyPrintHelper.getHTML(pageContent, url);
				pw.println(output);
				return null;
			}
		}catch(IOException ioe){
			log.severe("Error reading url:"+url+", "+ioe);
			output="Unexpected error" +ioe;
			return ERROR;
		}
		return SUCCESS;
	}

	private String readUrl(){
		StringBuffer content = new StringBuffer();
		try {
			URL pageUrl = new URL(url);
			URLConnection yc = pageUrl.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				content.append(inputLine);
			}
			in.close();
		} catch (Exception e) {
			log.severe("Error reading url:"+url+", "+e);
			return null;
		}
		return content.toString();
	}

	private String parse(String html){
		Parser parser = new Parser();
		try {
			parser.setInputHTML(html);
			NodeList list = parser.parse(null);

		} catch (ParserException e) {
			log.severe("Cannot parse html");
		}

		return null;
	}

	public String getOutput() {
		return output;
	}

	public void setOutput(String output) {
		this.output = output;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
}
